package com.aoxon.cargo.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.loader.FileLoader;

public class PurStoreGridAdapter extends BaseAdapter implements MyAdapter{

	private boolean isBusy = false;
	private List<Picture> pictures;
	private LayoutInflater layoutInflater;
	
	private FileLoader myImageLoader = new FileLoader(300, 300, true);
	
	public PurStoreGridAdapter(Context context, List<Picture> pictures){
		this.pictures = pictures;
		this.layoutInflater = LayoutInflater.from(context);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public void resetList(List<?> list) {
		// TODO Auto-generated method stub
		if(list != null){
			this.pictures.clear();
			this.pictures = (List<Picture>) list;
		}
		this.notifyDataSetChanged();
	}
	
	@Override
	public void setBusy(boolean isBusy){
		// TODO Auto-generated method stub
		this.isBusy = isBusy;
	}

	@Override
	public void clearCache(){
		// TODO Auto-generated method stub
		if(myImageLoader != null){
			myImageLoader.clearCache();
		}
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return pictures.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return pictures.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		
		ViewHolder viewHolder = null;
		
		if(convertView ==  null){
			viewHolder = new ViewHolder();
			convertView = layoutInflater.inflate(R.layout.pur_grid_store_item, null);
			viewHolder.view = (ImageView) convertView.findViewById(R.id.ivPurStoreGridItem);
			viewHolder.pBar = (ProgressBar) convertView.findViewById(R.id.pbPurStoreGridItem);
			convertView.setTag(viewHolder);
		}else{
			viewHolder = (ViewHolder) convertView.getTag();
		}

		try{
			
			String path =pictures.get(position).getPictureUrl() + "s.png";
			
			viewHolder.view.setImageResource(R.drawable.loading);
			if(!isBusy){
				myImageLoader.displayImage(path, viewHolder.view, viewHolder.pBar, false);
			}else{
				myImageLoader.displayImage(path, viewHolder.view, viewHolder.pBar, true);
			}
			
		}catch (Exception e){
			viewHolder.pBar.setVisibility(View.GONE);
			e.printStackTrace();
		}
		
		return convertView;
	}


	class ViewHolder{
		ImageView view;
		ProgressBar pBar;
	}
	
	
}
